package com.yc.demo.d0304;

import com.yc.demo.bean.User;
import com.yc.demo.d0303.LoginServlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.util.*;

@WebListener
public class OnlineListener implements HttpSessionAttributeListener {

    public static List<User> onlinedUser = new LinkedList<>();

    public OnlineListener() {
    }


    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        if (sbe.getName().equals("loginedUser")){
            LoginServlet.user.setName((String) sbe.getValue());

        }
        if (sbe.getName().equals("starttime")){
            LoginServlet.user.setStart((Long) sbe.getValue());
            System.out.println("记录开始时间"+sbe.getValue());
        }
        if (sbe.getName().equals("endtime")){
            System.out.println("记录结束时间"+sbe.getValue());
            LoginServlet.user.setEnd((Long) sbe.getValue());
            onlinedUser.add( LoginServlet.user);
            System.out.println(" 记录成功用户："+ sbe.getSession().getAttribute("loginedUser"));
            System.out.println("用户："+ LoginServlet.user.getName());
            System.out.println("开始："+ LoginServlet.user.getStart());
            System.out.println("结束："+ LoginServlet.user.getEnd());
        }
    }
    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {



    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        if (sbe.getName().equals("loginedUser")){
            String loginedUser = (String) sbe.getSession().getAttribute("loginedUser");
            //移除原来的名字
            onlinedUser.remove(loginedUser);
            //添加新的名字
//            onlinedUser.add((String) sbe.getValue());
        }
    }
}
